package com.wnxy.portal.rabbit.listener;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rabbitmq.client.Channel;
import com.wnxy.portal.common.enums.OrderStatusEnum;
import com.wnxy.portal.entity.Item;
import com.wnxy.portal.entity.Order;
import com.wnxy.portal.model.vo.CartItemVo;
import com.wnxy.portal.service.IItemService;
import com.wnxy.portal.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class CancelOrderListener {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IItemService itemService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = "order-dlx-queue")
    public void cancelOrder(String orderId, Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {
        log.info("超时未支付监听器，订单id：{}",orderId);
        //1. 获取订单id，根据订单id查询订单，获取订单状态
        // 查询订单
        Order order = orderService.getById(orderId);

        //2. 判断：如果状态是1，表示未支付
        if (order.getState() == OrderStatusEnum.NO_PAY.getCode()) {
            //2.1 修改订单状态为：7，已取消
            order.setState(OrderStatusEnum.ALREADY_CANCEL.getCode());
            orderService.updateById(order);

            //2.2 超时未支付，回退Redis库存。
            //分析: Redis中存储， storage bookId  库存
            List<Item> items = itemService.list(Wrappers.lambdaQuery(Item.class).eq(Item::getOrderId, orderId));
            items.forEach(item -> {
                // 获取购买数量
                Integer bcount = item.getBcount();
                // 回退Redis库存
                redisTemplate.opsForHash().increment("storage",item.getBookId().toString(),bcount);
            });
        }

        //3. 否则，已支付，不做处理， 直接手动应答
        channel.basicAck(deliveryTag,false);
    }
}
